<script setup lang="ts">
import { reactive, ref, onUnmounted } from 'vue';
import { ElForm, ElFormItem, ElInput, ElButton, ElLink, ElMessage, ElLoading } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { useRouter } from 'vue-router';

// 登录表单数据
const loginForm = reactive({
  phone: '',
  code: ''
});

// 表单验证规则
const formRules: FormRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '请输入6位数字验证码', trigger: 'blur' }
  ]
};

// 表单引用
const formRef = ref<FormInstance>();
// 倒计时控制
const countdown = ref(0);
// 定时器
let timer: NodeJS.Timeout | null = null;
// 路由实例
const router = useRouter();

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});

// 切换到密码登录
const switchToPasswordLogin = () => {
  router.push('/Register').catch(err => console.error('跳转失败:', err));
};

// 获取验证码
const getVerificationCode = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validateField('phone');

    const loading = ElLoading.service({
      lock: false,
      text: '发送中...',
      target: '.get-code-btn'
    });

    // 调用后端发送验证码接口
    const response = await fetch(
        `http://localhost:8020/SmsSend?mobile=${loginForm.phone}`,
        { method: 'GET' }
    );

    const result = await response.json();
    loading.close();

    if (response.ok && result.success) {
      ElMessage.success('验证码已发送，请注意查收（3分钟内有效）');
      startCountdown();
    } else {
      ElMessage.error(result.message || '验证码发送失败');
    }
  } catch (error) {
    console.error('发送验证码错误:', error);
    ElMessage.error('获取验证码失败，请重试');
  }
};

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60;
  if (timer) clearInterval(timer);

  timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer as NodeJS.Timeout);
      timer = null;
    }
  }, 1000);
};

// 处理登录逻辑（短信验证码方式）
const handleLogin = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    const loading = ElLoading.service({
      lock: true,
      text: '登录中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    // 1. 校验短信验证码
    const verifyResponse = await fetch(
        `http://localhost:8020/SmsVerify?mobile=${loginForm.phone}&code=${loginForm.code}`,
        { method: 'GET' }
    );
    const verifyResult = await verifyResponse.json();

    if (!verifyResult.success) {
      ElMessage.error(verifyResult.message || '验证码错误或已过期');
      loading.close();
      return;
    }

    // 2. 调用短信登录接口
    const loginResponse = await fetch('http://localhost:8020/user/SmsLogin', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        // 如果后端需要跨域带凭证，可开启，需和后端CORS配置一致
        // 'Credentials': 'include'
      },
      body: JSON.stringify({
        phone: loginForm.phone  // 仅传手机号
      })
    });
    console.log('Authorization:', loginResponse.headers.get('Authorization'));
    // 打印所有响应头，确认是否包含Authorization
    console.log('响应头列表:', Array.from(loginResponse.headers.entries()));

    // 3. 处理响应
    if (!loginResponse.ok) {
      const errorText = await loginResponse.text();
      ElMessage.error(`登录失败: ${loginResponse.status} - ${errorText}`);
      loading.close();
      return;
    }

    const loginResult = await loginResponse.json(); // 解析响应体
    const authorizationHeader = loginResponse.headers.get('Authorization');
    const token = authorizationHeader ? authorizationHeader.replace('Bearer ', '') : ''; // 提取 token

    loading.close();

    // 4. 存储 token 并跳转
    if (token) {
      localStorage.setItem('token', token);
      if (loginResult && loginResult.user) {
        localStorage.setItem('userInfo', JSON.stringify(loginResult.user));
      }
      ElMessage.success('登录成功');
      await router.push('/').catch(err => {
        console.error('跳转失败:', err);
        ElMessage.error('登录成功，但跳转首页失败，请手动前往');
      });
    } else {
      ElMessage.error('登录成功，但未获取到 token');
    }
  } catch (error) {
    console.error('登录请求错误:', error);
    ElMessage.error('登录失败，请检查网络或联系管理员');
  }
};
</script>

<template>
  <div class="login-container">
    <el-form
        ref="formRef"
        :model="loginForm"
        :rules="formRules"
        label-width="80px"
        class="login-form"
    >
      <h2 class="login-title">短信验证码登录</h2>
      <el-form-item label="手机号" prop="phone">
        <el-input
            v-model="loginForm.phone"
            placeholder="请输入手机号"
            prefix-icon="el-icon-phone"
            maxlength="11"
            clearable
        />
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-row :gutter="10">
          <el-col :span="14">
            <el-input
                v-model="loginForm.code"
                placeholder="请输入验证码"
                prefix-icon="el-icon-key"
                maxlength="6"
                clearable
            />
          </el-col>
          <el-col :span="10">
            <el-button
                type="default"
                class="get-code-btn"
                @click="getVerificationCode"
                :disabled="countdown > 0"
            >
              {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item>
        <el-link type="primary" @click="switchToPasswordLogin">用密码登录</el-link>
      </el-form-item>
      <el-form-item>
        <el-button
            type="primary"
            class="login-btn"
            @click="handleLogin"
        >
          登录
        </el-button>
      </el-form-item>
      <div class="extra-links">
        <el-link type="primary">找回密码</el-link>
        <el-link type="primary">更多选项</el-link>
      </div>
    </el-form>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
}

.login-form {
  width: 100%;
  max-width: 360px;
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
  font-size: 1.2rem;
  font-weight: 600;
  color: #333;
}

.login-btn,
.get-code-btn {
  width: 100%;
  margin-bottom: 10px;
}

.extra-links {
  text-align: center;
  margin-top: 15px;
  font-size: 14px;
}

@media (max-width: 480px) {
  .login-form {
    padding: 16px;
  }
  .login-title {
    font-size: 1rem;
    margin-bottom: 16px;
  }
}
</style>